package com.ybw.redis.prevent.repeat.service.impl;

import com.ybw.redis.prevent.repeat.config.PreventRepeatConfig;
import com.ybw.redis.prevent.repeat.constant.RedisPreConstant;
import com.ybw.redis.prevent.repeat.service.CommonService;
import com.ybw.redis.prevent.repeat.utils.MyStringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author ybw
 * @version V1.0
 * @className CommonServiceImpl
 * @date 2022/6/2
 **/
@Service
public class CommonServiceImpl implements CommonService {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private PreventRepeatConfig preventRepeatConfig;

    @Override
    public String generatePreCode() {
        //1、生成防重码
        String code = MyStringUtils.generateUUIDNoCenterLine();
        //2、获取redis key
        String preRedisKey = getPreRedisKey(code);
        //3、保存code到redis
        redisTemplate.opsForValue().set(preRedisKey, code, preventRepeatConfig.getTimeout(), TimeUnit.SECONDS);
        return code;
    }

    /**
     * 获取防重码redis key
     *
     * @param code
     * @methodName: getPreRedisKey
     * @return: java.lang.String
     * @author: ybw
     * @date: 2022/6/2
     **/
    private String getPreRedisKey(String code) {
        String md5 = MyStringUtils.md5(code, preventRepeatConfig.getSalt());
        return new StringBuffer().append(RedisPreConstant.PREVENT_REPEAT_CODE)
                .append(md5)
                .toString();
    }

    @Override
    public boolean checkExistAndDelKey(String code) {
        //1、获取redis key
        String preRedisKey = getPreRedisKey(code);
        //2、判断key存在
        boolean flag = redisTemplate.hasKey(preRedisKey);
        if (!flag) {
            return false;
        }
        redisTemplate.delete(preRedisKey);
        return true;
    }
}
